package com.oromwin.repos.spike;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionParams;

import com.oromwin.repos.common.ReposConfig;
import com.oromwin.repos.socket.SocketTestCase;
//6141,8653,6716,14290,10494
public class ReposHttpClient extends SocketTestCase {
    private static String url = "http://" + ReposConfig.getInstance().getReposHttpServerIP() + ":" + ReposConfig.getInstance().getReposHttpServerPort() + "/test";
    private static int DEFAULT_TIMEOUT = 3000;

    public ReposHttpClient(String name) {
        super(name);
    }

    protected void setUp() throws Exception {
        super.setUp();
    }

    protected void tearDown() throws Exception {
        super.tearDown();
    }

//  private void sendString() throws HttpException, IOException {
//  PostMethod method = new PostMethod(url);
//  RequestEntity stringEntity = new StringRequestEntity("stringrequestentity");
//  method.setRequestEntity(stringEntity);
//  try {
//  HttpClient client = new HttpClient();
//  int statusCode = client.executeMethod(method);
//  if (statusCode != HttpStatus.SC_OK) {
//  System.err.println("Method failed : " + method.getStatusLine());
//  } else {
//  System.out.println("Method succeeded : " + method.getStatusLine());
//  }
//  } catch (Exception e) {
//  e.printStackTrace();
//  }
//  }

    private void sendFile() throws FileNotFoundException {
        PostMethod method = new PostMethod(url);
        File file = new File(getROOTPATH() + INPUT);
//      String contentType = "text/plain";
        InputStream is = new FileInputStream(file);
//      long contentLength = file.length();
//      RequestEntity streamEntity = new InputStreamRequestEntity(is, contentLength, contentType);
        RequestEntity streamEntity = new InputStreamRequestEntity(is);
        method.setRequestEntity(streamEntity);
        try {
            HttpClient client = new HttpClient();
            client.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, DEFAULT_TIMEOUT);
            client.getParams().setParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, false);
            client.getParams().setParameter(HttpConnectionParams.TCP_NODELAY, true);
            int statusCode = client.executeMethod(method);
            if (statusCode != HttpStatus.SC_OK) {
                System.err.println("Method failed : " + method.getStatusLine());
            } else {
//              System.out.println("Method succeeded : " + method.getStatusLine());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void testSendFile() throws FileNotFoundException {
        long start = System.currentTimeMillis();
        for (int i = 0; i < COUNT; i++) {
            sendFile();
        }
        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }

//  public static void main(String[] args) {
//  // Create an instance of HttpClient.
//  HttpClient client = new HttpClient();

//  client.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, DEFAULT_TIMEOUT);
//  client.getParams().setParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, false);
//  client.getParams().setParameter(HttpConnectionParams.TCP_NODELAY, true);

//  // Create a method instance.
//  GetMethod method = new GetMethod(url);

//  // Provide custom retry handler is necessary
//  method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));

//  try {
//  // Execute the method.
//  int statusCode = client.executeMethod(method);

//  if (statusCode != HttpStatus.SC_OK) {
//  System.err.println("Method failed: " + method.getStatusLine());
//  }

//  if (false) {
//  // Read the response body.
//  byte[] responseBody = method.getResponseBody();
//  // Deal with the response.
//  // Use caution: ensure correct character encoding and is not binary data
//  File output = new File("output.txt");
//  Writer writer = new FileWriter(output);
//  writer.write(new String(responseBody));
//  writer.close();
//  } else {
//  File output = new File("/home/psyoblade/workspace/java/eclipse/Repository-0.1.0/ok");
//  OutputStream fos = new FileOutputStream(output);
//  Header[] header = method.getResponseHeaders();
//  log.info(header.toString());
//  InputStream is = method.getResponseBodyAsStream();
//  int chunkedSize = is.read();
//  while (chunkedSize > 0) {
//  byte[] b = new byte[chunkedSize];
//  int readBytes = is.read(b);
//  log.info(String.format("readBytes{%d}", readBytes));
//  fos.write(b); // byte를 자르다보면, 한글이 잘릴 수도...-_-;;
//  chunkedSize = is.read();
//  }
//  fos.close();
//  }

//  } catch (HttpException e) {
//  System.err.println("Fatal protocol violation: " + e.getMessage());
//  e.printStackTrace();
//  } catch (IOException e) {
//  System.err.println("Fatal transport error: " + e.getMessage());
//  e.printStackTrace();
//  } finally {
//  // Release the connection.
//  method.releaseConnection();
//  }
//  }

    public static void main(String[] args) throws FileNotFoundException {
//      System.out.println("Starting transfer " + COUNT + " files");
        ReposHttpClient rhc = new ReposHttpClient("ReposHttpClient");
        rhc.testSendFile();
//      System.out.println("Completed.");
        System.exit(0);
    }
}
